/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */
package com.fuyao.cloud.personnel.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyao.cloud.admin.api.feign.RemoteUserInfoService;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.excel.vo.ErrorMessage;
import com.fuyao.cloud.personnel.api.constant.CertificateConstant;
import com.fuyao.cloud.personnel.api.entity.CertificateInfo;
import com.fuyao.cloud.personnel.api.entity.CertificateLendRecord;
import com.fuyao.cloud.personnel.api.vo.excel.CertificateInfoExcelVO;
import com.fuyao.cloud.personnel.mapper.CertificateInfoMapper;
import com.fuyao.cloud.personnel.mapper.CertificateLendRecordMapper;
import com.fuyao.cloud.personnel.service.CertificateInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 证件信息
 *
 * @author 碎月
 * @date 2022-01-12 15:47:16
 */
@Service
public class CertificateInfoServiceImpl extends ServiceImpl<CertificateInfoMapper, CertificateInfo> implements CertificateInfoService {

    @Autowired
    private CertificateLendRecordMapper lendRecordMapper;

    @Resource
    private RemoteUserInfoService userInfoService;

    /**
     * 借用
     * @param lendRecordInfo 借用记录信息
     * @return
     */
    @Override
    public Integer lend(CertificateLendRecord lendRecordInfo) {
        if (lendRecordInfo==null){
            return CertificateConstant.FAILD_NULL_CODE;
        }
        if (lendRecordInfo.getCertificateInfoId()==null || lendRecordInfo.getCertificateInfoId()==0){
            return CertificateConstant.FAILD_ID_CODE;
        }
        // 更新状态
        CertificateInfo certificateInfo= this.baseMapper.selectById(lendRecordInfo.getCertificateInfoId());
        certificateInfo.setLendStatus(CertificateConstant.LEND_STATUS[1]);
        this.baseMapper.updateById(certificateInfo);
        // 保存记录
        this.lendRecordMapper.insert(lendRecordInfo);
        return CertificateConstant.SUCCESS_CODE;
    }

    /**
     * 归还
     * @param id 证件id
     * @return
     */
    @Override
    public Integer giveBack(Long id) {
        if (id == null || id == 0){
            return CertificateConstant.FAILD_ID_CODE;
        }
        // 更新状态
        CertificateInfo certificateInfo = this.baseMapper.selectById(id);
        certificateInfo.setLendStatus(CertificateConstant.LEND_STATUS[0]);
        this.baseMapper.updateById(certificateInfo);
        // 更新实际归还时间
        long count = this.lendRecordMapper.selectCount(Wrappers.<CertificateLendRecord>lambdaQuery()
                .eq(CertificateLendRecord::getCertificateInfoId,id));
        CertificateLendRecord lendRecord=this.lendRecordMapper.selectList(Wrappers.<CertificateLendRecord>lambdaQuery()
                .eq(CertificateLendRecord::getCertificateInfoId,id)).get((int) (count-1));
        lendRecord.setActualReturnTime(LocalDateTime.now());
        this.lendRecordMapper.updateById(lendRecord);
        return CertificateConstant.SUCCESS_CODE;
    }

    @Override
    public Page lendRecordPage(Page page, Long certificateInfoId) {
        return this.lendRecordMapper.selectPage(page,Wrappers.<CertificateLendRecord>lambdaQuery().eq(CertificateLendRecord::getCertificateInfoId,certificateInfoId));
    }

    @Override
    public R importCertificateInfo(List<CertificateInfoExcelVO> excelVOList, BindingResult bindingResult) {
        // 通用校验获取失败的数据
        List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();

        for (int i = 0; i < excelVOList.size(); i++) {
            CertificateInfoExcelVO infoExcelVO = excelVOList.get(i);
            Set<String> errorMsg = new HashSet<>();
//            Long userInfoId = (Long) this.userInfoService.getUserinfoId(infoExcelVO.getIdNumber()).getData();
//            if (userInfoId == null){
//                errorMsg.add(String.format("人员编号不存在"));
//            }
            // 数据合法情况
            if (CollUtil.isEmpty(errorMsg)) {
                insertExcelCertificateInfo(infoExcelVO);
            }
            else {
                // 数据不合法情况
                errorMessageList.add(new ErrorMessage((long) (i + 2), errorMsg));
            }

        }

        if (CollUtil.isNotEmpty(errorMessageList)) {
            return R.failed(errorMessageList);
        }
        return R.ok();
    }

    private void insertExcelCertificateInfo(CertificateInfoExcelVO infoExcelVO) {
        CertificateInfo certificateInfo =new CertificateInfo();
        BeanUtils.copyProperties(infoExcelVO,certificateInfo);
        this.baseMapper.insert(certificateInfo);
    }
}
